package com.weirdor.boot.module.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.weirdor.boot.common.utils.Constant;
import com.weirdor.boot.common.utils.StrUtils;
import com.weirdor.boot.module.entity.SysMenu;
import com.weirdor.boot.module.entity.SysUser;
import com.weirdor.boot.module.entity.SysUserToken;
import com.weirdor.boot.module.service.IShiroService;
import com.weirdor.boot.module.service.ISysMenuService;
import com.weirdor.boot.module.service.ISysUserService;
import com.weirdor.boot.module.service.ISysUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShiroServiceImpl implements IShiroService {

    @Autowired
    private ISysMenuService sysMenuService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserTokenService sysUserTokenService;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            EntityWrapper<SysMenu> ew=new EntityWrapper<>();
            List<SysMenu> menuList = sysMenuService.selectList(ew);
            permsList = new ArrayList<>(menuList.size());
            for(SysMenu menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = userService.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StrUtils.isEmpty(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserToken queryByToken(String accessToken) {
        SysUserToken sysUserToken=new SysUserToken();
        sysUserToken.setToken(accessToken);
        EntityWrapper<SysUserToken> ew=new EntityWrapper<>();
        ew.eq("token",accessToken);
        return sysUserTokenService.selectOne(ew);
    }

    @Override
    public SysUser queryUser(Long userId) {
        return userService.selectById(userId);
    }

}
